<?php
/**
 * 利润服务层
 * @author maniac
 */
namespace app\common\service;

use app\common\model\Orders AS OrdersModel;
use app\common\model\OrderGoods AS OrderGoodsModel;
use app\facade\Site AS SiteFacade;
use app\common\model\Members AS MembersModel;
use app\common\model\MemberProfits AS MemberProfitsModel;
use app\common\model\MemberCash AS MemberCashModel;

class Profit extends Base
{
    /**
     * 获取收益列表
     * @param array  $where 查询条件
     * @param string $limit 分页条件
     */
    public function profitList($where = '', $limit = '')
    {
        $data = MemberProfitsModel::field('profit,total,remark,datetime')->append(['datetime_txt'])->where($where)->order('id DESC')->limit($limit)->select();
        return $data;
    }
    
    /**
     * 自动分润
     */
    public function autoProfit()
    {
        // 昨天 0 点的时间戳
        $yesterdayUnix   = strtotime(date('Y-m-d', time() - 24*60*60));
        // 今天 0 点的时间戳
        $todayUnix       = strtotime(date('Y-m-d', time()));
        $where           = [
            ['pay_status', 'eq', 1],
            ['create_time', 'egt', $yesterdayUnix],
            ['create_time', 'lt', $todayUnix],
        ];
        $orderIds = OrdersModel::where($where)->column('id');
        $where    = [
            ['order_id', 'in', $orderIds],
        ];
        $orderGoods  = OrderGoodsModel::field('cost_price,sale_price,goods_nums')->where($where)->select();
        // 平台总利润
        $totalProfit = 0;
        foreach ($orderGoods as $v) {
            $totalProfit += ($v['sale_price'] - $v['cost_price']) * $v['goods_nums'];
        }
        $appInfo = SiteFacade::appInfo();
        // 股东分成
        $profit  = ceil(($totalProfit * ($appInfo['day_separate_rate']/100))*100)/100;
        // 查询所有股东会员
        $members = MembersModel::field('id,wechat_id,profit')->where('role_id', 2)->select();
        $add     = [];
        $update  = [];
        foreach ($members as $v) {
            $where = [
                'wechat_id' => $v['wechat_id'],
                'datetime'  => $yesterdayUnix,
            ];
            $info  = MemberProfitsModel::field('id')->where($where)->find();
            if (!$info) {
                $add[]    = [
                    'userid'      => $v['id'],
                    'wechat_id'   => $v['wechat_id'],
                    'shop_profit' => $totalProfit,
                    'profit'      => $profit,
                    'total'       => $v['profit'] + $profit,
                    'remark'      => '平台每日利润分成',
                ];
                $update[] = [
                    'id'     => $v['id'],
                    'profit' => $v['profit'] + $profit,
                ];
            }
        }
        if (!empty($add)) {
            (new MemberProfitsModel)->saveAll($add);
        }
        
        if (!empty($update)) {
            (new MembersModel)->saveAll($update);
        }
    }
    
    /**
     * 申请提现
     * @param int    $userId 申请会员
     * @param double $money  提现金额
     */
    public function cash($userId, $money)
    {
        $money = (float)$money;
        if (!$money) {
            exception('请输入提现金额');
        }
        $member = MembersModel::field('id,profit')->where('wechat_id', $userId)->find();
        if ($money > $member['profit']) {
            exception('收益余额不足');
        }
        $appInfo = SiteFacade::appInfo();
        if ($money < $appInfo['min_cash_money']) {
            exception('最小提现'.$appInfo['min_cash_money'].'元');
        }
        $create = [
            'userid'    => $member['id'],
            'wechat_id' => $userId,
            'money'     => $money,
        ];
        $info = MemberCashModel::create($create);
        if ($info) {
            $member->profit = $member['profit'] - $money;
            if ($member->save()) {
                return true;
            }
        }
        return false;
    }
}
